import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { collectGoodsList, getGoodsCollect, toggleCollectGoods } from '@/api/modules/user'
import type { CollectGoods } from '@/types/collect'
import { useUserStore } from './user'
import { ElMessage } from 'element-plus'

export const useCollectStore = defineStore('collect', () => {
  const collectItems = ref<CollectGoods[]>([])
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  const total = ref(0)
  const userStore = useUserStore()

  // 获取收藏总数
  const collectCount = computed(() => total.value)

  // 获取收藏列表（分页）
  async function fetchCollectList(page = 1, size = 10) {
    // 检查是否有 token
    if (!userStore.token) {
      collectItems.value = []
      return
    }

    try {
      isLoading.value = true
      error.value = null
      const response:any = await collectGoodsList({ page, size })
      if (response.code === 1000) {
        collectItems.value = response.data.list
        total.value = response.data.pagination.total
      } else {
        error.value = response.message || '获取收藏列表失败'
      }
    } catch (err) {
      error.value = '获取收藏列表失败'
      console.error('获取收藏列表失败:', err)
    } finally {
      isLoading.value = false
    }
  }

  // 检查商品是否已收藏
  async function checkIsCollected(goodsId: number) {
    if (!userStore.token) return false

    try {
      const response:any = await getGoodsCollect(goodsId)
      console.log("response", response)
      return response.code === 1000 && response.data !== null && response.data.id !== null
    } catch (err) {
      console.error('检查商品收藏状态失败:', err)
      return false
    }
  }

  // 收藏/取消收藏商品
  async function toggleCollect(goodsId: number) {
    // 检查是否有 token
    if (!userStore.token) {
      ElMessage.warning('请先登录')
      return false
    }

    try {
      const response:any = await toggleCollectGoods(goodsId)
      if (response.code === 1000) {
        await fetchCollectList() // 重新获取收藏列表
        ElMessage.success(response.data.message)
        return true
      }
      ElMessage.error(response.message || '操作失败')
      return false
    } catch (err) {
      console.error('收藏操作失败:', err)
      ElMessage.error('操作失败')
      return false
    }
  }

  return {
    collectItems,
    isLoading,
    error,
    collectCount,
    total,
    fetchCollectList,
    checkIsCollected,
    toggleCollect
  }
}, {
  persist: true
}) 